package com.milkshopbackend.milkshop.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milkshopbackend.milkshop.Service.ProductImageService;
import com.milkshopbackend.milkshop.entity.ProductImage;
import com.milkshopbackend.milkshop.mapper.ProductImageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class ProductImageServiceImpl extends ServiceImpl<ProductImageMapper, ProductImage> implements ProductImageService {

    @Value("${upload.path:/uploads}")
    private String uploadPath;

    @Override
    public String uploadImage(MultipartFile file) {
        try {
            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = Paths.get(uploadPath, filename);
            Files.copy(file.getInputStream(), filePath);

            // 返回文件URL
            return "/uploads/" + filename;
        } catch (IOException e) {
            throw new RuntimeException("Failed to upload image", e);
        }
    }

    @Override
    public void addProductImage(Long productId, String imageUrl, Integer imageType, Integer sort) {
        ProductImage productImage = new ProductImage();
        productImage.setProductId(productId);
        productImage.setImageUrl(imageUrl);
        productImage.setImageType(imageType);
        productImage.setSort(sort);
        productImage.setCreateTime(LocalDateTime.now());
        productImage.setUpdateTime(LocalDateTime.now());
        save(productImage);
    }

    @Override
    public List<ProductImage> getProductImages(Long productId) {
        LambdaQueryWrapper<ProductImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductImage::getProductId, productId)
                .orderByAsc(ProductImage::getSort);
        return list(wrapper);
    }

    @Override
    public void deleteProductImage(Long imageId) {
        ProductImage image = getById(imageId);
        if (image != null) {
            // 删除文件
            String filePath = uploadPath + image.getImageUrl();
            try {
                Files.deleteIfExists(Paths.get(filePath));
            } catch (IOException e) {
                // 记录日志但不抛出异常
                log.error("Failed to delete image file: " + filePath, e);
            }
            // 删除数据库记录
            removeById(imageId);
        }
    }
} 